package com.elitecrm.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ognl.Ognl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class OgnlUtil {
	private static final Log log = LogFactory.getLog(OgnlUtil.class);
	public static String parseString(String source, Map<String,Object> context){
		try{
        	Pattern p = Pattern.compile("\\$\\{([\\w]*)\\}");
    		Matcher matcher = p.matcher(source);
    		while(matcher.find()){
    			int gc = matcher.groupCount();
    			if(gc>=1){
    				String ognlExpress = matcher.group(1);
    				Object ognlResult = Ognl.getValue(ognlExpress,context);
    				if(ognlResult == null){
    					ognlResult = "";
    				}
    				source = source.replaceAll("\\$\\{"+ognlExpress+"\\}",ognlResult.toString());
    			}
    		}
        }catch(Exception e){
        	log.error("",e);
        }
        return source;
	}
	
	public static void main(String[] args) {
		Map<String,Object> context = new HashMap<String,Object>();
		context.put("id", "001");
		context.put("name", "lori");
		context.put("age", 28);
		String source = "My id is ${id}, my name is ${name} and my age is ${age}... another name ${name}";
		source = parseString(source, context);
		System.out.println(source);
	}
}
